import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken, setTime } from '@/utils/auth'
const state = {
  token: getToken() || null,
  UserInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    // 退出清空token与userInfo
    state.token = null
    state.UserInfo = {}
    removeToken()
  },
  setUserInfo(state, data) {
    state.UserInfo = { ...data }
  }
}
const actions = {
  async login(store, data) {
    // 错误捕获
    store.commit('permission/routerList', [], { root: true })
    const res = await login(data)
    store.commit('setToken', res)
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const UserDetail = await getUserDetailById(res.userId)
    const data = {
      ...res,
      ...UserDetail
    }
    store.commit('setUserInfo', data)
    setTime()
    return res
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

